# encoding: utf-8

from pub.trans import TransBase, json2dict

from util.log import getLogger
logger = getLogger()

class SayHelloTrans(TransBase):
    """ 简单通讯协议Demo
    """
    def __init__(self):
        super().__init__()

    def reply(self, msg: bytes, sock1addr=None):
        # logger.debug("接收到消息：【{}】".format(msg))
        msg_type, msg_body = self.sock.msg_split(msg)

        if self.check_cmd(msg):
            dict_msg = json2dict(msg_body)
            if dict_msg["type"] == "cmd":
                self.reply_command(dict_msg, sock1addr)
            else:
                err = "Unkown command [{}]".format(msg)
                self.send_error(err.encode(), sock1addr)

        elif self.check_data(msg):
            # logger.debug("转发数据【{}】".format(msg))
            self.server_recv_data(msg_body, sock1addr)

        else:
            err = "Unkown request [{}]".format(msg)
            self.send_error(err.encode(), sock1addr)

    def parse_reply(self, msg: bytes):
        # logger.debug("接收到回复：【{}】".format(msg))
        msg_type, msg_body = self.sock.msg_split(msg)

        if self.check_cmd(msg):
            dict_msg = json2dict(msg_body)
            if dict_msg["type"] == "cmd":
                self.on_command(dict_msg)
            else:
                print("未解析命令【{}】".format(msg))

        elif self.check_data(msg):
            # logger.debug("接收到数据【{}】".format(msg_body))
            self.client_recv_data(msg_body)

        else:
            logger.error("Fail to parse the message【{}】.".format(msg))

    def command(self):
        dict_msg = {
            "type": "cmd",
            "msg" : "hello"
        }
        self.send_cmd(dict_msg)
        self._zmq_mode()

    def reply_command(self, dict_msg, sock1addr):
        logger.debug("Recv Request：【{}】".format(dict_msg['msg']))
        dict_msg["msg"] = "world"
        self.send_cmd(dict_msg, sock1addr)

    def on_command(self, dict_msg):
        print("Recv Reply：【{}】".format(dict_msg['msg']))

    def request(self, data):
        self.send_data(data)
        self._zmq_mode()

    def _zmq_mode(self):
        from util.socket import ZmqFrame

        if isinstance(self.sock, ZmqFrame):  # one by one
            data = self.sock.recv()
            self.parse_reply(data)

    def server_recv_data(self, data, sock1addr):
        print("Recv Data：【{}】from【{}】".format(data, sock1addr))
        # 将输入字符转大写
        self.send_data(data.upper(), sock1addr)

    def client_recv_data(self, data):
        print("Recv Data：【{}】from Server".format(data))
